package com.lyh.notes.interceptor;

import com.lyh.notes.scope.RequestScopeData;
import com.lyh.notes.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RequestScopeData requestScopeData;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token==null){
            requestScopeData.setToken(null);
            requestScopeData.setUserId(null);
            requestScopeData.setLogin(false);
            return true;
        }
        token=token.replace("Bearer ", "");
        if(jwtUtil.validateToken(token)){
            Long userId = jwtUtil.getUserIdFromToken(token);
            requestScopeData.setToken(token);
            requestScopeData.setUserId(userId);
            requestScopeData.setLogin(true);
        }else{
            requestScopeData.setLogin(false);
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
